<{capture name="header"}>
<{css app="ome" src="ome.css"}>
<{css app="ome" src="style.css"}>
<{script src="coms/autocompleter.js" app="desktop"}>
<{script src="coms/pager.js" app="desktop"}>
<{/capture}>
<form id="fm1" name="form1" action="index.php?app=console&ctl=admin_purchase&act=doEdit" method="POST">
<input type="hidden" name="po_id" value="<{$po.po_id}>" />
<div class="tableform">
<h3>编辑采购订单</h3>
    <div class="division">
      <h5>基本信息</h5>
      <table border="0" cellspacing="0" cellpadding="0" class="gridlist">
      <thead>
        <tr>
          <td width="10%" align="right" nowrap="nowrap">采购单名称:</td>
          <td colspan="3"><span id="exigence" style="color:red; display:none">！</span>
            <input type="text" size="32" onblur="checkName(this.value);" id="purchase_name" name="purchase_name" value="<{if $po.name}><{$po.name}><{else}><{$cur_date}><{/if}>" />
            <input type="checkbox" name="emergency" value="true" onchange="chgexigence(this);" <{if $po.emergency=='true'}>checked="checked"<{/if}> />
            紧急采购</td>
        </tr>
        <tr>
          <td align="right">供应商:</td>
          <td width="40%"><{$supplier_detail.name}><div style="position:relative;display:none;"><{input type="text" hidden="hidden" id="supplier" name="supplier" vtype="required" value="{$supplier_detail.name}"}>
              <input type="hidden" name="supplier_id" id="supplier_id" value="<{$supplier_detail.supplier_id}>" />
              <span style="color:red;">*</span> <a title="查看供应商列表" class="btn_supplier" target="_blank"><{img id="copy" app="desktop" title="供应商列表" src="bundle/zoom_btn.gif"}></a> </div></td>
          <td align="right">采购方式:</td>
          <td><{if $po.po_type=='cash'}>现购 <{else}>赊购<{/if}></td>
        </tr>
        <tr>
          <td width="10%" align="right">到货仓库:</td>
          <td>
            <{if $branch_mode=='single'}>
                <{$po.branch_name}>
                <input type="hidden" name="branch" value="<{$po.branch_id}>" />
            <{else}>
                <{if count($branch)>5}>
                <{input type="select" name="branch" vtype="required" rows=$branch valueColumn="branch_id" labelColumn="name" value=""}> <span style="color:red">*</span>
                <{else}>
                <{foreach from=$branch item=items}>
                <input type="radio" name="branch" vtype="requiredradio" value="<{$items.branch_id}>" />
                <{$items.name}>
                <{/foreach}> <span style="color:red">*</span>
                <{/if}>
            <{/if}></td>
          <td align="right" nowrap="nowrap" title="一次性物流费用">物流费用:</td>
          <td><input type="text" vtype="number" name="d_cost" size="6" value="<{$po.delivery_cost}>" />
            元</td>
        </tr>
        <tr >
          <td align="right"><span class="endd" style="display:none;">预付款:</span></td>
          <td><span class="endd" style="display:none;">
            <{if $po.po_type=='cash' || $po.statement!=1 || $po.deposit_balance >0}><{$po.deposit|cur}><{else}>
            <input type="text" vtype="required" name="price" size="6" value="<{$po.deposit}>" /><{/if}>
            元  <span style="color:red">*</span></span></td>
          <td align="right" nowrap="nowrap">预计到货天数:</td>
          <td><input type="hidden" id="arrive" name="arrive" value="" />
            <input type="text" size="2" id="arrive_days" value="<{$po.diff_days}>" name="arrive_days"  onchange="pushDate(this);" maxlength="3" />
            天 <b id="pushdate"></b></td>


        </tr>
        </thead>
      </table>

<h5 style="margin-top:10px;">采购商品</h5>
      <{button label="供应商频道" id="supplier-find-btn" }>
      <{button label="基础物料库频道" id="purchase-find-btn" }>
      <span id='pfba'>
          <label>按基础物料编码索引：</label>
          <input type="text" name="bn" />
      </span> 
      <span id='pfba2'>
          <label>按基础物料名称索引：</label>
          <input type="text" name="name" size="35"/>
      </span>
      <span id='pfba3'>
          <label>按条码索引：</label>
          <input name="barcode" type="text" size="35" />
      </span>
      <table class="gridlist" id="purchase_table"  style="margin:4px 0;">
        <thead>
          <tr>
          <th><input type="checkbox" class='selectall' onclick="this.blur()">
            <th>基础物料编码</th>
            <th style="width:240px;">基础物料名称</th>
            <th>规格</th>
            <th>条形码</th>
            <th>数量</th>
            <th>单价</th>
            <th>合计</th>
            <th style="width:30px;">删除</th>
          </tr>
        </thead>
        <tbody id="dataNode">
          <tr>
            <td colspan="8" style="padding:0;"><div class="note" style="margin:0;"> 暂无采购货品信息 </div></td>
          </tr>
        </tbody>
      </table>
      <div align="right">
        购买总量: <span id="buy_count">0</span> 总金额: <span id="buy_amount">0</span> &nbsp; <{button label="删除选中" id="purchase-del-btn"}> &nbsp;<{button type="button" id="purchase-delall-btn" label="全部删除" }></div> </div>
      <table width="100%" border="0" cellpadding="0" cellspacing="0" style="margin-top:10px;">
      <{if $po.memo}>
      <tr>
      	<td width="10%" align="right">备注：</td>
      	<td align="left"><{foreach from=$po.memo item=items}>
      	<b><{$items.op_content|escape:"HTML"}></b>
      	<{$items.op_time}> by <{$items.op_name}><br/>
      	<{/foreach}></td>
      </tr>
      <{/if}>
      <tr>
        <td width="10%" align="right"><{if $po.memo}>追加<{/if}>备注:</td>
        <td align="left"><textarea id="memo" maxth="255" rows="3" cols="80%" name="memo"></textarea></td>
      </tr>
      <tr>
        <td align="right">经办人:</td>
        <td align="left"><input name="operator" type="text" value="<{$po.operator}>" size="15" vtype="required"/></td>
      </tr>
    </table>
    <div id="cc" class="noprint table-action"> <{button type="button" class="btn" id="purchase-save-btn" label="保 存"}> &nbsp; <{button type="button" class="btn" id="return-btn" label="关 闭" onclick="javascript:void(window.close());"}></div>

</div>
</form>

<script>
(function(){
var visiTips = new Tips({
		onShow:function(tip,el){
			el.addClass('active');
			tip.setStyle('display','block');
		},
		text: function(element){
			if(element.get('visibility')=='false'){
				return '不可售商品';
			}else{
				return '';
			}
		}
	});
  var tpl='<tr key="{product_id}" id="product_{product_id}" status="{delete}" title="{title}">'+
        '<td><input type="checkbox" class="product_select"></td>  <td>{bn}</td><td class="product-name" visibility="{visibility}">{name}</td><td>{spec_info}</td><td>{barcode}</td>'+
        '  <td><input type="text" value="{num}" key="num" vtype="unsigned&amp;&amp;required" tname="at[_PRIMARY_]" size="6" /></td>'+
        '  <td><input type="text" vtype="number&amp;&amp;required" tname="pr[_PRIMARY_]" key="price" value="{price}" size="8" />元</td>'+
        '  <td class="count">{count}</td>'+
        '  <td><div style="display:{deleter};"><{img src="bundle/delecate.gif" app="desktop" class="pointer btn-delete-item" key="state"}></td>'+
        '</tr>';

    var callurl='index.php?app=console&ctl=admin_purchase&act=getProducts',store=[],pag,rows;

    new Request({url:'index.php?app=console&ctl=admin_purchase&act=getEditProducts&p[0]='+<{$po.po_id}>,
    onComplete:function(rs){
        rs=JSON.decode(rs);
        store.combine(rs);
        createProduct(store);
    }}).send();

    var options={
        'getVar':'bn',
        'fxOptions':false,
        callJSON:function(){return window.autocompleter_json;},
        injectChoice:function(json){
            var choice = new Element('li', {'html': this.markQueryValue(json[this.options.getVar])});
            choice.store('_data',json);
            choice.inputValue = json[this.options.getVar];
            this.addChoiceEvents(choice).inject(this.choices);
        },
        onHide:function(){
            if(!this.selected) return;
            var json=this.selected.retrieve('_data');
            json=$splat(json);
            init(json);
            MessageBox.success('加载商品成功!!');
        },
        onFocus:function(ipt){
            ipt.value='';
        }
    };

    new Autocompleter.script($E('#supplier'),"index.php?app=console&ctl=admin_purchase&act=getSupplier", {
        'getVar':'name',
        'fxOptions':false,
        callJSON:function(){return window.autocompleter_json;},
        injectChoice:function(json){
            var brief=json["brief"]?"("+json["brief"]+")":"";
            var choice = new Element('li', {'html': this.markQueryValue(json[this.options.getVar]+brief)});
            choice.inputValue = json[this.options.getVar];
            this.addChoiceEvents(choice).inject(this.choices);
            $('supplier_id').set("value",json["supplier_id"]);
            $('arrive_days').set("value",json["arrive_days"]);
            pushDate($('arrive_days'));
        },
        onHide:function(){
          if(!this.selected)return;
		  var json=this.selected.retrieve('_data');
          $('supplier_id').set("value",json["supplier_id"]);
        }
    });
    new Autocompleter.script($E('#pfba input'),callurl,options);
    new Autocompleter.script($E('#pfba2 input'),callurl,$merge(options,{'getVar':'name'}));
    new Autocompleter.script($E('#pfba3 input'),callurl,$merge(options,{'getVar':'barcode'}));

    $('purchase-find-btn').addEvent('click',function(e){
       var url='index.php?app=desktop&act=alertpages&goto='+encodeURIComponent('index.php?app=console&ctl=admin_purchase&act=findMaterial');
	   Ex_Loader('modedialog',function() {
		   new finderDialog(url,{params:{url:callurl,name:'product_id[]'},width:1000,height:660,
		   onCallback:function(rs){
			   if(!rs)return;
			   rs=JSON.decode(rs);
			   init(rs);
		   }});
	   });
    });

    //从供应商查找商品
    $('supplier-find-btn').addEvent('click',function(e){
        if ($("supplier").get("value").trim().length===0 || $("supplier_id").get("value").trim().length===0){
            $('supplier').addClass("error_supplier");
            MessageBox.error("请先填写正确的供应商！");
            return false;
        }
        $('supplier').removeClass("error_supplier");
        var supplier_id = $('supplier_id').value;
        var url='index.php?app=desktop&act=alertpages&goto='+encodeURIComponent('index.php?app=console&ctl=admin_purchase&act=findMaterial&p[0]='+supplier_id);
		Ex_Loader('modedialog',function() {
			new finderDialog(url,{params:{url:callurl,name:'product_id[]'},width:1000,height:660,
			onCallback:function(rs){
				if(!rs)return;
				rs=JSON.decode(rs);
				init(rs);
			}});
		});
    });

    $E(".btn_supplier").addEvent('click',function(e){
        var url='?app=desktop&act=alertpages&goto='+encodeURIComponent("index.php?app=console&ctl=admin_supplier&singleselect=1");
        Ex_Loader('modedialog',function() {
	    	new finderDialog(url,{params:{url:'index.php?app=console&ctl=admin_purchase&act=getSupplierById',name:'id',type:'radio'},handle:'supplier',width:1000,height:500});
		});
    });

    function emptyData(){
        var noData='<tr>'+
            '<td colspan="8" style="padding:0;"><div class="note" style="margin:0;"> 暂无采购货品信息 </div></td>'+
            '</tr>';
        $('dataNode').set('html',noData);
    }
    var _next_key = next_key =  product_id = last_key = null;
    function createProduct(data){
        pag=new PageData(tpl,data,{'updateMain':$('dataNode'),'pageNum':10000,
            'format':function(d){
                if(d['delete']=="0"){
                    d.title="不可选择";
                    d.deleter='none';
                }
                else{
                    d.title="点击选取/反选此条记录";
                    d.deleter='';
                }
                d.count = (d.num * d.price).toFixed(2);
                d['price'] = (d.price * 1).toFixed(2);
            },
            'onShow':function(){
                var _this=this;
                $$('#dataNode input[tname$="[_PRIMARY_]"]').each(function(item){
                    item.store('initval',item.value).addEvent('change',function(e){
                        var patten,
                            parent = this.getParent('tr'),
                            pid= parent.get('key'),
                            value= this.value,
                            diffval = this.retrieve('initval') - value;
                        if (/^at\[/.test(this.get('tname'))){
                            patten = /^[1-9]\d*$/;
                        }else{
                            patten = /^\d+(\.*)\d*$/;
                        }
                        if(!patten.test(value)){
                            this.focus();
                            this.select();
                            return MessageBox.error('输入格式有误！');
                        }
                        this.store('initval', value);
                        _this.editData(pid,[this.get('key'),value]);

                        var count = parent.getElement('td.count'),
                            num = _this.selectData(pid).num.toInt(),
                            pr = (_this.selectData(pid).price.toFloat() *1).toFixed(2);
                            sums = (num * pr).toFixed(2);

                        count.set('text',sums);
                        _this.editData(pid,['count',sums]);
                        if (/^at\[/.test(this.get('tname'))){
                            $('buy_count').set('text', $('buy_count').get('text') - diffval);
                            $('buy_amount').set('text', ($('buy_amount').get('text') - diffval * pr).toFixed(2));
                        }else{
                            $('buy_amount').set('text', ($('buy_amount').get('text') - diffval * num).toFixed(2));
                        }
                    });
                });

                $$('#dataNode tr').each(function(item,i){
                    if(item.get('status')!=='0') item.addEvent('click',function(e){
                        //e.stop();
                        if(_next_key){
                            $E('#product_'+_next_key).set('style','');
                            delete _next_key;//马上删除这个临时变量
                        }

                        this.toggleClass('selected');
                        _this.selectData(this.get('key')).selected = _this.selectData(this.get('key')).selected && _this.selectData(this.get('key')).selected === true ? false : true;
                        
                        var selectflag = _this.selectData(this.get('key')).selected;
                        var selectproduct = item.getElement('.product_select');
                        if (selectflag)
                        {
                            selectproduct.set('checked','checked');
                        }else{
                            selectproduct.set('checked','');
                        }

                    });
                    if(item.getElement('.btn-delete-item')) item.getElement('.btn-delete-item').addEvent('click',function(e){
                        e.stop();
                        product_id = 'product_'+item.get('key');
                        _next_key = $$('#'+product_id+'+tr').get('key');

                        if(_this.selectData(item.get('key')) && confirm('确定要删除 '+ _this.selectData(item.get('key'))['name'] +' 吗？')){
                        	compute(item);
                            _this.delData(item.get('key'));

                            //删除数据后，定位到删除下面的那一条记录
                            if(isNaN(_next_key) == false){
                            	next_key = 'product_'+_next_key; 
                                $E('#'+next_key).set('style','background:none repeat scroll 0 0 #6699FF;color:#FFFFCC');           	
                            }else{
                            	_next_key = null;
                            }
                            product_id =  next_key = null;
                        }
                        if(!$E('#dataNode tr')) emptyData();
                    });
                    item.getElement('input[tname^=at]').addEvent('enter',function(e){
                        $E('#pfba input').focus();
                    });
                });
                $E('#dataNode input[key^=num]').focus();

                (function(){
                    var sum = 0, amounts = 0;
                    _this.data.each(function(d,i){
                        sum += _this.selectData(d['product_id']).num.toInt();
                    });
                    $('buy_count').set('text',sum);

                    $$('#dataNode td.count').each(function(item,i){
                        amounts += parseFloat(item.get('text'));
                    });
                    $('buy_amount').set('text',amounts.toFixed(3));
                }).delay(100);

			  $ES('.product-name').each(function(item){
					if(item.get('visibility')=='false'){
						item.setStyle('color','#808080');
					}
			  });
			  $ES('.product-name').removeEvent('mouseover').addEvent('mouseover',function(e){
					if (this.get('visibility')=='false')
					{
						var e  = new Event(e), el = e.target;
						visiTips.attach(el);
						el.addEvent('mouseleave',function(){
							this.removeClass('active');
						});
						el.fireEvent('mouseenter',e);
					}
			  });
           }
        });
    }
    function init(rs){
        var tmparr=findProduct(rs,'product_id');
        store.unshift.apply(store,tmparr);
        createProduct(store);
    }
    function findProduct(arr,PRIMARY){
        if(!store.length)return arr;
        store.each(function(a){
           arr.each(function(b){
               if(a[PRIMARY]==b[PRIMARY])arr.erase(b);
           });
        });
        return arr;
    }

    function delProduct(obj,arr){
        arr.each(function(d){obj.delData(d);});
    }

    $E('.selectall').addEvent('click',function(e){
    
       if (this.checked)
        {
            $ES('.product_select').set('checked','checked');
            $$('.product_select').each(function(item){
                protr = item.getParent('tr');
                product_id = protr.get('key');
                protr.addClass('selected');
                pag.selectData(product_id).selected=true;
            
            });
        }else{
            $ES('.product_select').set('checked','');
            $$('.product_select').each(function(item){
                protr = item.getParent('tr');
                product_id = protr.get('key');
                protr.removeClass('selected');
                pag.selectData(product_id).selected=false;
            
            });
        }
        
    
    
    });

    $('purchase-delall-btn').addEvent('click',function(e){
        if(!pag||!pag.curdata) return;
        var delarr=[];
        var rows = $$('#dataNode tr');
        pag.data.each(function(d,i){
            if(rows[i].get('status')=='1'){
                delarr.push(d['product_id']);
            }
        });
        if(delarr.length){
            if(confirm('确认删除全部未入库的采购商品吗？')){
                delProduct(pag,delarr);
                $('buy_count').set('text',0);
                $('buy_amount').set('text',0);
                if(!$E('#dataNode tr')) emptyData();
            }
        }
        else MessageBox.error("没有可以删除的采购商品！");
    });
    function compute(e){
        var num = e.getElement('input[tname="at[_PRIMARY_]"]').value.toInt();
        var pr = e.getElement('input[tname="pr[_PRIMARY_]"]').value.toFloat();
        var sum = num * pr;
        $('buy_count').set('text',$('buy_count').get('text') - num);
        $('buy_amount').set('text',($('buy_amount').get('text') - sum).toFixed(3));
    }
    
    $('purchase-del-btn').addEvent('click',function(e){
        if(!pag||!pag.data)return;
        var delarr=[];
        pag.data.each(function(d,i){
            if(pag.selectData(d['product_id']).selected && pag.selectData(d['product_id']).selected === true) delarr.push(d['product_id']);
        });
        //获取批量删除中的最后一个节点
        last_key =  	$$('.selected').getLast();
        last_key = last_key.get('key');

        if(delarr.length){
            if(confirm('确认删除选定的采购商品吗？')){
            	var total=0,prices=0,amounts=0;
                delarr.each(function(id,i){
                  total += pag.selectData(id).num.toInt();
                  prices += pag.selectData(id).price.toFloat();
                  amounts += (pag.selectData(id).num * pag.selectData(id).price).toFixed(3);
                });
                //找到本次批量删除最后一条记录下面的那条记录
                product_id = 'product_'+last_key;
                _next_key = $$('#'+product_id+'+tr').get('key');

                $('buy_count').set('text',$('buy_count').get('text') - total);
                $('buy_amount').set('text',$('buy_amount').get('text') - amounts);
                delProduct(pag,delarr);
                if(isNaN(_next_key) == false){
                    next_key = 'product_'+_next_key; 
                    //对本次批量删除最后一条记录下面的那条记录，颜色加深提示
                    $E('#'+next_key).set('style','background:none repeat scroll 0 0 #6699FF;color:#FFFFCC');           	
                }else{
                    _next_key = null;
                }
                product_id = next_key=last_key = null;
            }
            if(!$E('#dataNode tr')) emptyData();
        }
        else MessageBox.error("请先选择欲删除的采购商品！");
    });

    $('purchase-save-btn').addEvent('click',function(e){
        var _this=this;
        var form=this.getParent('form');
        if(pag){
            var data=pag.toHideInput($('dataNode').getElement('tr'));
            form.store('target',{extraData:data,
              onRequest:function(){
                    _this.disabled=true;
                },
                onComplete:function(jsontext){
                    try{
                        var json = Json.evaluate(jsontext);
                        if (typeof(json.error) != 'undefined'){
                            _this.disabled=false;
                        }else{
                            _this.disabled=true;
                            opener.finderGroup['<{$env.get.finder_id}>'].refresh.delay(400,opener.finderGroup['<{$env.get.finder_id}>']);
                            setTimeout('window.close()',500);
                        }
                    }catch(e){}
                }
            });
        }
        form.fireEvent('submit',e);
    });
})();

function chgexigence(o){
    o.checked?$("exigence").setStyle('display',""):$("exigence").setStyle('display',"none");
}
function validSupplier(element){
    element=$(element);
    new Element('span',{'class':'error caution notice-inline','html':'本项必填'}).injectAfter(element);
    element.removeEvents('blur').addEvent('blur',function(){
        //element.setStyle("background","#FBE3E4");
       if(validate(element)){
           //element.setStyle("background","#fff");
           element.removeEvent('blur',arguments.callee);
       }
    });
}
//validSupplier('supplier');

function pushDate(o){
    if (typeof(o) !== 'object'){
        o = $('arrive_days');
    }
    if(o.value!==""){
        if(/^\d*$/.test(o.value)){
        var ftime = new Date(Date.parse(new Date())+86400000 * o.value.toInt());
        var realtime = ftime.getFullYear()+'-'+(ftime.getMonth()+1)+'-'+ftime.getDate()+' '+ftime.toLocaleTimeString();
        $("pushdate").set("text",realtime);
            //$("arrive").set("value", new Date(new Date.parse(new Date())+86400000 * o.value)) ;
        }
        else o.value="";
    }
    else $("pushdate").empty();
}

function prichange(ss){
    if (ss == 1){
        $$('.endd').setStyle('display','none');
        $('price').set('value', '');
    }else{
        $$('.endd').setStyle('display', '');
    }
}

function checkName(thisval){
    if(/!|！/.test(thisval)){
        var val = thisval.replace("!","");
        val = val.replace("！","");
        $('purchase_name').set('value', val);
    }
}

//赊购方式触发事件
<{if $po.po_type=='credit' or $po.po_type==''}>
prichange('2');
<{/if}>
<{if $po.diff_days}>
pushDate(<{$po.diff_days}>);
<{/if}>

/*
//根据供应商显示采购员
$('supplier').addEvent('change', function(){
    var sid = this.get('value');
    if (sid)
    var jsonRequest = new Request.JSON({
       url: 'index.php?app=purchase&ctl=admin_supplier&act=getOperator',
       onComplete: function(result, text){
          $('operator').set('value', result.operator);
       }
    }).get({
        'sid': sid
       });
});
*/
</script>
